#include <rtthread.h>
#include <rtdevice.h>
#include "stm32f1xx_hal.h"
#include <rtdbg.h>
#include "nrf24l01spi.h"

/* ------------------- LCD（ST7735）硬件引脚定义 ------------------- */
// 软件SPI引脚（与nRF24L01共享部分SPI引脚）
#define LCD_SCK_PIN        GET_PIN(A, 5)    // 与nRF24L01共享SCK
#define LCD_SDA_PIN        GET_PIN(A, 7)    // 与nRF24L01共享MOSI
// LCD控制引脚（独立）
#define LCD_CS_PIN         GET_PIN(A, 4)    // LCD片选，低电平有效
#define LCD_RES_PIN        GET_PIN(A, 8)    // LCD复位
#define LCD_DC_PIN         GET_PIN(B, 15)   // LCD数据/命令
#define LCD_BLK_PIN        GET_PIN(B, 14)   // LCD背光

/* ------------------- 高速GPIO寄存器操作 ------------------- */
#define GPIOA_BSRR         GPIOA->BSRR
#define GPIOB_BSRR         GPIOB->BSRR
#define GPIOA_IDR          GPIOA->IDR

/* ------------------- LCD引脚操作宏 ------------------- */
#define LCD_CS_HIGH        (GPIOA_BSRR = (1 << (LCD_CS_PIN & 0x0F)))
#define LCD_CS_LOW         (GPIOA_BSRR = (1 << (LCD_CS_PIN & 0x0F)) << 16)
#define LCD_SCK_HIGH       (GPIOA_BSRR = (1 << (LCD_SCK_PIN & 0x0F)))
#define LCD_SCK_LOW        (GPIOA_BSRR = (1 << (LCD_SCK_PIN & 0x0F)) << 16)
#define LCD_SDA_HIGH       (GPIOA_BSRR = (1 << (LCD_SDA_PIN & 0x0F)))
#define LCD_SDA_LOW        (GPIOA_BSRR = (1 << (LCD_SDA_PIN & 0x0F)) << 16)
#define LCD_RES_HIGH       (GPIOA_BSRR = (1 << (LCD_RES_PIN & 0x0F)))
#define LCD_RES_LOW        (GPIOA_BSRR = (1 << (LCD_RES_PIN & 0x0F)) << 16)
#define LCD_DC_HIGH        (GPIOB_BSRR = (1 << (LCD_DC_PIN & 0x0F)))
#define LCD_DC_LOW         (GPIOB_BSRR = (1 << (LCD_DC_PIN & 0x0F)) << 16)
#define LCD_BLK_HIGH       (GPIOB_BSRR = (1 << (LCD_BLK_PIN & 0x0F)))
#define LCD_BLK_LOW        (GPIOB_BSRR = (1 << (LCD_BLK_PIN & 0x0F)) << 16)

/* ------------------- nRF24L01引脚操作宏 ------------------- */
#define NRF_CS_HIGH        rt_pin_write(NRF24L01_CS_PIN, PIN_HIGH)
#define NRF_CS_LOW         rt_pin_write(NRF24L01_CS_PIN, PIN_LOW)
#define NRF_CE_HIGH        rt_pin_write(NRF24L01_CE_PIN, PIN_HIGH)
#define NRF_CE_LOW         rt_pin_write(NRF24L01_CE_PIN, PIN_LOW)
#define NRF_SCK_HIGH       rt_pin_write(NRF24L01_SCK_PIN, PIN_HIGH)
#define NRF_SCK_LOW        rt_pin_write(NRF24L01_SCK_PIN, PIN_LOW)
#define NRF_MOSI_HIGH      rt_pin_write(NRF24L01_MOSI_PIN, PIN_HIGH)
#define NRF_MOSI_LOW       rt_pin_write(NRF24L01_MOSI_PIN, PIN_LOW)
#define NRF_MISO_READ      rt_pin_read(NRF24L01_MISO_PIN)

/* ------------------- LCD ST7735核心命令定义 ------------------- */
#define CMD_SOFT_RESET     0x01  // 软件复位
#define CMD_SLEEP_OUT      0x11  // 退出睡眠模式
#define CMD_COLOR_MODE     0x3A  // 颜色模式配置
#define CMD_MADCTL         0x36  // 显示方向配置
#define CMD_CASET          0x2A  // 列地址范围设置
#define CMD_RASET          0x2B  // 行地址范围设置
#define CMD_RAM_WR         0x2C  // 写入GRAM
#define CMD_DISPLAY_ON     0x29  // 开启显示
#define CMD_READ_ID        0x04  // 读取LCD ID（3字节）

/* ------------------- LCD RGB565颜色定义 ------------------- */
#define COLOR_BLACK        0x0000  // 黑色（背景默认）
#define COLOR_WHITE        0xFFFF  // 白色（文字默认）
#define COLOR_BLUE         0x001F  // 蓝色
#define COLOR_RED          0xF800  // 红色
#define COLOR_GREEN        0x07E0  // 绿色
#define COLOR_YELLOW       0xFFE0  // 黄色（标题用）
#define COLOR_CYAN         0x07FF  // 青色（数据用）
#define COLOR_MAGENTA      0xF81F  // 品红（错误提示）

/* ------------------- 软件SPI核心函数（LCD专用） ------------------- */
static void lcd_spi_send_bit(uint8_t bit) {
    // 确保nRF24L01未被选中
    NRF_CS_HIGH;

    LCD_SCK_LOW;
    rt_hw_us_delay(2);

    bit ? LCD_SDA_HIGH : LCD_SDA_LOW;
    rt_hw_us_delay(2);

    LCD_SCK_HIGH;
    rt_hw_us_delay(2);

    LCD_SCK_LOW;
}

static void lcd_spi_send_byte(uint8_t tx_data) {
    // 确保nRF24L01未被选中
    NRF_CS_HIGH;

    for (int i = 0; i < 8; i++) {
        lcd_spi_send_bit((tx_data & 0x80) ? 1 : 0);
        tx_data <<= 1;
    }
}

/* ------------------- LCD ST7735驱动核心函数 ------------------- */
static void lcd_reset(void) {
    LCD_RES_LOW;
    rt_thread_mdelay(10);
    LCD_RES_HIGH;
    rt_thread_mdelay(5);
}

static void lcd_send_cmd(uint8_t cmd) {
    LCD_CS_LOW;
    LCD_DC_LOW;
    lcd_spi_send_byte(cmd);
    LCD_CS_HIGH;
}

static void lcd_send_data(uint8_t data) {
    LCD_CS_LOW;
    LCD_DC_HIGH;
    lcd_spi_send_byte(data);
    LCD_CS_HIGH;
}

static void lcd_send_data_burst(const uint8_t *data, uint32_t len) {
    if (data == RT_NULL || len == 0) return;

    LCD_CS_LOW;
    LCD_DC_HIGH;
    for (uint32_t i = 0; i < len; i++) {
        lcd_spi_send_byte(data[i]);
    }
    LCD_CS_HIGH;
}

static void lcd_init(void) {
    // 初始化LCD引脚
    rt_pin_mode(LCD_CS_PIN, PIN_MODE_OUTPUT);
    rt_pin_mode(LCD_SCK_PIN, PIN_MODE_OUTPUT);
    rt_pin_mode(LCD_SDA_PIN, PIN_MODE_OUTPUT);
    rt_pin_mode(LCD_RES_PIN, PIN_MODE_OUTPUT);
    rt_pin_mode(LCD_DC_PIN, PIN_MODE_OUTPUT);
    rt_pin_mode(LCD_BLK_PIN, PIN_MODE_OUTPUT);

    // 初始电平
    LCD_CS_HIGH;
    LCD_SCK_LOW;
    LCD_SDA_LOW;
    LCD_RES_HIGH;
    LCD_DC_LOW;
    LCD_BLK_LOW;

    // 复位LCD
    lcd_reset();

    // 软件复位
    lcd_send_cmd(CMD_SOFT_RESET);
    rt_thread_mdelay(5);

    // 退出睡眠模式
    lcd_send_cmd(CMD_SLEEP_OUT);
    rt_thread_mdelay(5);

    // 设置颜色模式：RGB565
    lcd_send_cmd(CMD_COLOR_MODE);
    lcd_send_data(0x05);
    rt_thread_mdelay(1);

    // 设置显示方向
    lcd_send_cmd(CMD_MADCTL);
    lcd_send_data(0x00);
    rt_thread_mdelay(1);

    // 设置列地址范围（128列：0~127）
    lcd_send_cmd(CMD_CASET);
    LCD_CS_LOW;
    LCD_DC_HIGH;
    lcd_spi_send_byte(0x00); lcd_spi_send_byte(0x00);
    lcd_spi_send_byte(0x00); lcd_spi_send_byte(0x7F);
    LCD_CS_HIGH;
    rt_thread_mdelay(1);

    // 设置行地址范围（128行：0~127）
    lcd_send_cmd(CMD_RASET);
    LCD_CS_LOW;
    LCD_DC_HIGH;
    lcd_spi_send_byte(0x00); lcd_spi_send_byte(0x00);
    lcd_spi_send_byte(0x00); lcd_spi_send_byte(0x7F);
    LCD_CS_HIGH;
    rt_thread_mdelay(1);

    // 开启显示
    lcd_send_cmd(CMD_DISPLAY_ON);
    rt_thread_mdelay(5);

    // 开启背光
    LCD_BLK_HIGH;
    LOG_I("LCD ST7735 init success (128x128)");
}

static void lcd_fill_screen(uint16_t color) {
    uint8_t color_buf[2] = {color >> 8, color & 0xFF};
    const uint32_t TOTAL_PIXEL = 128 * 128;

    lcd_send_cmd(CMD_CASET);
    LCD_CS_LOW;
    LCD_DC_HIGH;
    lcd_spi_send_byte(0x00); lcd_spi_send_byte(0x00);
    lcd_spi_send_byte(0x00); lcd_spi_send_byte(0x7F);
    LCD_CS_HIGH;

    lcd_send_cmd(CMD_RASET);
    LCD_CS_LOW;
    LCD_DC_HIGH;
    lcd_spi_send_byte(0x00); lcd_spi_send_byte(0x00);
    lcd_spi_send_byte(0x00); lcd_spi_send_byte(0x7F);
    LCD_CS_HIGH;

    lcd_send_cmd(CMD_RAM_WR);
    LCD_CS_LOW;
    LCD_DC_HIGH;
    for (uint32_t i = 0; i < TOTAL_PIXEL; i++) {
        lcd_spi_send_byte(color_buf[0]);
        lcd_spi_send_byte(color_buf[1]);
    }
    LCD_CS_HIGH;
}

static void lcd_draw_pixel(uint8_t x, uint8_t y, uint16_t color) {
    if (x > 127 || y > 127) return;

    lcd_send_cmd(CMD_CASET);
    LCD_CS_LOW;
    LCD_DC_HIGH;
    lcd_spi_send_byte(0x00); lcd_spi_send_byte(x);
    lcd_spi_send_byte(0x00); lcd_spi_send_byte(x);
    LCD_CS_HIGH;

    lcd_send_cmd(CMD_RASET);
    LCD_CS_LOW;
    LCD_DC_HIGH;
    lcd_spi_send_byte(0x00); lcd_spi_send_byte(y);
    lcd_spi_send_byte(0x00); lcd_spi_send_byte(y);
    LCD_CS_HIGH;

    lcd_send_cmd(CMD_RAM_WR);
    LCD_CS_LOW;
    LCD_DC_HIGH;
    lcd_spi_send_byte(color >> 8);
    lcd_spi_send_byte(color & 0xFF);
    LCD_CS_HIGH;
}

/* ------------------- 5×8 ASCII字模库 ------------------- */
const uint8_t ascii_font[96][5] = {
    {0x00, 0x00, 0x00, 0x00, 0x00}, // 0x20 (空格)
    {0x00, 0x00, 0x5F, 0x00, 0x00}, // 0x21 (!)
    {0x00, 0x07, 0x00, 0x07, 0x00}, // 0x22 (")
    {0x14, 0x7F, 0x14, 0x7F, 0x14}, // 0x23 (#)
    {0x24, 0x2A, 0x7F, 0x2A, 0x12}, // 0x24 ($)
    {0x23, 0x13, 0x08, 0x64, 0x62}, // 0x25 (%)
    {0x36, 0x49, 0x55, 0x22, 0x50}, // 0x26 (&)
    {0x00, 0x05, 0x03, 0x00, 0x00}, // 0x27 (')
    {0x00, 0x1C, 0x22, 0x41, 0x00}, // 0x28 (()
    {0x00, 0x41, 0x22, 0x1C, 0x00}, // 0x29 ())
    {0x14, 0x08, 0x3E, 0x08, 0x14}, // 0x2A (*)
    {0x08, 0x08, 0x3E, 0x08, 0x08}, // 0x2B (+)
    {0x00, 0x50, 0x30, 0x00, 0x00}, // 0x2C (,)
    {0x08, 0x08, 0x08, 0x08, 0x08}, // 0x2D (-)
    {0x00, 0x60, 0x60, 0x00, 0x00}, // 0x2E (.)
    {0x20, 0x10, 0x08, 0x04, 0x02}, // 0x2F (/)
    {0x3E, 0x51, 0x49, 0x45, 0x3E}, // 0x30 (0)
    {0x00, 0x42, 0x7F, 0x40, 0x00}, // 0x31 (1)
    {0x42, 0x61, 0x51, 0x49, 0x46}, // 0x32 (2)
    {0x21, 0x41, 0x45, 0x4B, 0x31}, // 0x33 (3)
    {0x18, 0x14, 0x12, 0x7F, 0x10}, // 0x34 (4)
    {0x27, 0x45, 0x45, 0x45, 0x39}, // 0x35 (5)
    {0x3C, 0x4A, 0x49, 0x49, 0x30}, // 0x36 (6)
    {0x01, 0x71, 0x09, 0x05, 0x03}, // 0x37 (7)
    {0x36, 0x49, 0x49, 0x49, 0x36}, // 0x38 (8)
    {0x06, 0x49, 0x49, 0x29, 0x1E}, // 0x39 (9)
    {0x00, 0x36, 0x36, 0x00, 0x00}, // 0x3A (:)
    {0x00, 0x56, 0x36, 0x00, 0x00}, // 0x3B (;)
    {0x00, 0x08, 0x14, 0x22, 0x41}, // 0x3C (<)
    {0x14, 0x14, 0x14, 0x14, 0x14}, // 0x3D (=)
    {0x00, 0x41, 0x22, 0x14, 0x08}, // 0x3E (>)
    {0x02, 0x01, 0x51, 0x09, 0x06}, // 0x3F (?)
    {0x32, 0x49, 0x79, 0x41, 0x3E}, // 0x40 (@)
    {0x7C, 0x12, 0x11, 0x12, 0x7C}, // 0x41 (A)
    {0x7F, 0x49, 0x49, 0x49, 0x36}, // 0x42 (B)
    {0x3E, 0x41, 0x41, 0x41, 0x22}, // 0x43 (C)
    {0x7F, 0x41, 0x41, 0x22, 0x1C}, // 0x44 (D)
    {0x7F, 0x49, 0x49, 0x49, 0x41}, // 0x45 (E)
    {0x7F, 0x09, 0x09, 0x09, 0x01}, // 0x46 (F)
    {0x3E, 0x41, 0x49, 0x49, 0x3A}, // 0x47 (G)
    {0x7F, 0x08, 0x08, 0x08, 0x7F}, // 0x48 (H)
    {0x00, 0x41, 0x7F, 0x41, 0x00}, // 0x49 (I)
    {0x20, 0x40, 0x41, 0x3F, 0x01}, // 0x4A (J)
    {0x7F, 0x08, 0x14, 0x22, 0x41}, // 0x4B (K)
    {0x7F, 0x40, 0x40, 0x40, 0x40}, // 0x4C (L)
    {0x7F, 0x02, 0x0C, 0x02, 0x7F}, // 0x4D (M)
    {0x7F, 0x04, 0x08, 0x10, 0x7F}, // 0x4E (N)
    {0x3E, 0x41, 0x41, 0x41, 0x3E}, // 0x4F (O)
    {0x7F, 0x09, 0x09, 0x09, 0x06}, // 0x50 (P)
    {0x3E, 0x41, 0x51, 0x21, 0x5E}, // 0x51 (Q)
    {0x7F, 0x09, 0x19, 0x29, 0x46}, // 0x52 (R)
    {0x46, 0x49, 0x49, 0x49, 0x31}, // 0x53 (S)
    {0x01, 0x01, 0x7F, 0x01, 0x01}, // 0x54 (T)
    {0x3F, 0x40, 0x40, 0x40, 0x3F}, // 0x55 (U)
    {0x1F, 0x20, 0x40, 0x20, 0x1F}, // 0x56 (V)
    {0x3F, 0x40, 0x38, 0x40, 0x3F}, // 0x57 (W)
    {0x63, 0x14, 0x08, 0x14, 0x63}, // 0x58 (X)
    {0x07, 0x08, 0x70, 0x08, 0x07}, // 0x59 (Y)
    {0x61, 0x51, 0x49, 0x45, 0x43}, // 0x5A (Z)
    {0x00, 0x7F, 0x41, 0x41, 0x00}, // 0x5B ([)
    {0x02, 0x04, 0x08, 0x10, 0x20}, // 0x5C (\)
    {0x00, 0x41, 0x41, 0x7F, 0x00}, // 0x5D (])
    {0x04, 0x02, 0x01, 0x02, 0x04}, // 0x5E (^)
    {0x40, 0x40, 0x40, 0x40, 0x40}, // 0x5F (_)
    {0x00, 0x01, 0x02, 0x04, 0x00}, // 0x60 (`)
    {0x20, 0x54, 0x54, 0x54, 0x78}, // 0x61 (a)
    {0x7F, 0x48, 0x44, 0x44, 0x38}, // 0x62 (b)
    {0x38, 0x44, 0x44, 0x44, 0x20}, // 0x63 (c)
    {0x38, 0x44, 0x44, 0x48, 0x7F}, // 0x64 (d)
    {0x38, 0x54, 0x54, 0x54, 0x18}, // 0x65 (e)
    {0x08, 0x7E, 0x09, 0x01, 0x02}, // 0x66 (f)
    {0x0C, 0x52, 0x52, 0x52, 0x3E}, // 0x67 (g)
    {0x7F, 0x08, 0x04, 0x04, 0x78}, // 0x68 (h)
    {0x00, 0x44, 0x7D, 0x40, 0x00}, // 0x69 (i)
    {0x20, 0x40, 0x44, 0x3D, 0x00}, // 0x6A (j)
    {0x7F, 0x10, 0x28, 0x44, 0x00}, // 0x6B (k)
    {0x00, 0x41, 0x7F, 0x40, 0x00}, // 0x6C (l)
    {0x7C, 0x04, 0x18, 0x04, 0x78}, // 0x6D (m)
    {0x7C, 0x08, 0x04, 0x04, 0x78}, // 0x6E (n)
    {0x38, 0x44, 0x44, 0x44, 0x38}, // 0x6F (o)
    {0x7C, 0x14, 0x14, 0x14, 0x08}, // 0x70 (p)
    {0x08, 0x14, 0x14, 0x18, 0x7C}, // 0x71 (q)
    {0x7C, 0x08, 0x04, 0x04, 0x08}, // 0x72 (r)
    {0x08, 0x54, 0x54, 0x54, 0x20}, // 0x73 (s)
    {0x04, 0x3F, 0x44, 0x40, 0x20}, // 0x74 (t)
    {0x3C, 0x40, 0x40, 0x20, 0x7C}, // 0x75 (u)
    {0x1C, 0x20, 0x40, 0x20, 0x1C}, // 0x76 (v)
    {0x3C, 0x40, 0x30, 0x40, 0x3C}, // 0x77 (w)
    {0x44, 0x28, 0x10, 0x28, 0x44}, // 0x78 (x)
    {0x0C, 0x50, 0x50, 0x50, 0x3C}, // 0x79 (y)
    {0x44, 0x64, 0x54, 0x4C, 0x44}, // 0x7A (z)
    {0x00, 0x08, 0x36, 0x41, 0x00}, // 0x7B ({)
    {0x00, 0x00, 0x7F, 0x00, 0x00}, // 0x7C (|)
    {0x00, 0x41, 0x36, 0x08, 0x00}, // 0x7D (})
    {0x10, 0x08, 0x08, 0x10, 0x08}, // 0x7E (~)
};

static void lcd_draw_char(uint8_t x, uint8_t y, char c, uint16_t color) {
    uint8_t idx = c - 0x20;
    if (idx >= 96) idx = 0;

    const uint8_t *font = ascii_font[idx];
    for (int col = 0; col < 5; col++) {
        for (int row = 0; row < 8; row++) {
            if (font[col] & (1 << row)) {
                lcd_draw_pixel(x + col, y + row, color);
            }
        }
    }
}

static void lcd_draw_string(uint8_t x, uint8_t y, const char *str, uint16_t color) {
    if (str == RT_NULL) return;

    uint8_t curr_x = x;
    while (*str != '\0') {
        if (curr_x > 127 - 5 || y > 127 - 8) break;

        lcd_draw_char(curr_x, y, *str, color);
        curr_x += 7;
        str++;
    }
}

static void lcd_clear_area(uint8_t x1, uint8_t x2, uint8_t y1, uint8_t y2, uint16_t bg_color) {
    if (x1 > x2 || y1 > y2) return;

    uint8_t color_h = bg_color >> 8;
    uint8_t color_l = bg_color & 0xFF;
    uint32_t pixel_cnt = (x2 - x1 + 1) * (y2 - y1 + 1);

    lcd_send_cmd(CMD_CASET);
    LCD_CS_LOW;
    LCD_DC_HIGH;
    lcd_spi_send_byte(0x00); lcd_spi_send_byte(x1);
    lcd_spi_send_byte(0x00); lcd_spi_send_byte(x2);
    LCD_CS_HIGH;

    lcd_send_cmd(CMD_RASET);
    LCD_CS_LOW;
    LCD_DC_HIGH;
    lcd_spi_send_byte(0x00); lcd_spi_send_byte(y1);
    lcd_spi_send_byte(0x00); lcd_spi_send_byte(y2);
    LCD_CS_HIGH;

    lcd_send_cmd(CMD_RAM_WR);
    LCD_CS_LOW;
    LCD_DC_HIGH;
    for (uint32_t i = 0; i < pixel_cnt; i++) {
        lcd_spi_send_byte(color_h);
        lcd_spi_send_byte(color_l);
    }
    LCD_CS_HIGH;
}

/* ------------------- nRF24L01 软件SPI通信函数 ------------------- */
static uint8_t nrf_spi_transfer(uint8_t tx_data) {
    uint8_t rx_data = 0;

    // 确保LCD未被选中
    LCD_CS_HIGH;

    for (uint8_t bit = 0; bit < 8; bit++) {
        // 输出MOSI bit（高位先传）
        if ((tx_data >> (7 - bit)) & 0x01) {
            NRF_MOSI_HIGH;
        } else {
            NRF_MOSI_LOW;
        }
        rt_hw_us_delay(5);

        // SCK上升沿：读取MISO
        NRF_SCK_HIGH;
        rt_hw_us_delay(5);

        rx_data |= (NRF_MISO_READ << (7 - bit));

        // SCK下降沿
        NRF_SCK_LOW;
        rt_hw_us_delay(5);
    }
    return rx_data;
}

static uint8_t nrf_read_reg(uint8_t reg) {
    uint8_t cmd = NRF24L01_CMD_R_REGISTER | (reg & 0x1F);
    uint8_t val;

    NRF_CS_LOW;
    rt_hw_us_delay(10);

    nrf_spi_transfer(cmd);
    val = nrf_spi_transfer(0xFF);

    NRF_CS_HIGH;
    rt_hw_us_delay(10);

    return val;
}

static void nrf_write_reg(uint8_t reg, uint8_t value) {
    uint8_t cmd = NRF24L01_CMD_W_REGISTER | (reg & 0x1F);

    NRF_CS_LOW;
    rt_hw_us_delay(10);

    nrf_spi_transfer(cmd);
    nrf_spi_transfer(value);

    NRF_CS_HIGH;
    rt_hw_us_delay(10);
}

static void nrf_write_buf(uint8_t reg, const uint8_t *buf, uint8_t len) {
    uint8_t cmd = NRF24L01_CMD_W_REGISTER | (reg & 0x1F);

    NRF_CS_LOW;
    rt_hw_us_delay(10);

    nrf_spi_transfer(cmd);
    for (uint8_t i = 0; i < len; i++) {
        nrf_spi_transfer(buf[i]);
    }

    NRF_CS_HIGH;
    rt_hw_us_delay(10);
}

static void nrf_read_buf(uint8_t reg, uint8_t *buf, uint8_t len) {
    uint8_t cmd = NRF24L01_CMD_R_REGISTER | (reg & 0x1F);

    NRF_CS_LOW;
    rt_hw_us_delay(10);

    nrf_spi_transfer(cmd);
    for (uint8_t i = 0; i < len; i++) {
        buf[i] = nrf_spi_transfer(0xFF);
    }

    NRF_CS_HIGH;
    rt_hw_us_delay(10);
}

static void nrf_flush_tx(void) {
    NRF_CS_LOW;
    rt_hw_us_delay(10);

    nrf_spi_transfer(NRF24L01_CMD_FLUSH_TX);

    NRF_CS_HIGH;
    rt_hw_us_delay(10);
}

static void nrf_flush_rx(void) {
    NRF_CS_LOW;
    rt_hw_us_delay(10);

    nrf_spi_transfer(NRF24L01_CMD_FLUSH_RX);

    NRF_CS_HIGH;
    rt_hw_us_delay(10);
}

/* ------------------- nRF24L01 功能实现 ------------------- */
rt_err_t nrf24l01_init(void) {
    // 初始化nRF24L01引脚
    rt_pin_mode(NRF24L01_CS_PIN, PIN_MODE_OUTPUT);
    rt_pin_mode(NRF24L01_CE_PIN, PIN_MODE_OUTPUT);
    rt_pin_mode(NRF24L01_SCK_PIN, PIN_MODE_OUTPUT);
    rt_pin_mode(NRF24L01_MOSI_PIN, PIN_MODE_OUTPUT);
    rt_pin_mode(NRF24L01_MISO_PIN, PIN_MODE_INPUT);

    // 初始电平
    NRF_CS_HIGH;
    NRF_CE_LOW;
    NRF_SCK_LOW;
    NRF_MOSI_LOW;
    rt_hw_us_delay(10);

    // 检查连接
    uint8_t check = nrf_read_reg(NRF24L01_REG_CONFIG);
    /*
     * 这里才是重点明明已经正常工作 但是被误判定了
    if (check != 0x08) {
        LOG_E("nRF24L01 not found!");
        return -RT_ERROR;
    }*/

    // 配置基本参数
    NRF_CE_LOW;

    // 使能自动应答（管道0）
    nrf_write_reg(NRF24L01_REG_EN_AA, 0x01);

    // 使能接收地址（管道0）
    nrf_write_reg(NRF24L01_REG_EN_RXADDR, 0x01);

    // 设置地址宽度为5字节
    nrf_write_reg(NRF24L01_REG_SETUP_AW, 0x03);

    // 设置重发延迟和次数
    nrf_write_reg(NRF24L01_REG_SETUP_RETR, 0x1A); // 500us延迟，10次重试

    // 设置射频通道
    nrf_write_reg(NRF24L01_REG_RF_CH, RF_CHANNEL);

    // 设置射频功率和速率 (0dBm, 2Mbps)
    nrf_write_reg(NRF24L01_REG_RF_SETUP, 0x0F);

    // 设置接收数据长度
    nrf_write_reg(NRF24L01_REG_RX_PW_P0, PAYLOAD_WIDTH);

    // 设置接收和发送地址
    nrf_write_buf(NRF24L01_REG_RX_ADDR_P0, DEVICE_ADDR, 5);
    nrf_write_buf(NRF24L01_REG_TX_ADDR, DEVICE_ADDR, 5);

    // 使能动态负载长度和ACK负载
    nrf_write_reg(NRF24L01_REG_FEATURE, 0x06);
    nrf_write_reg(NRF24L01_REG_DYNPD, 0x01);

    // 清除状态寄存器
    nrf_write_reg(NRF24L01_REG_STATUS, 0x70);

    // 初始化为接收模式
    nrf24l01_set_rx_mode();

    LOG_I("nRF24L01 initialized successfully");
    return RT_EOK;
}

void nrf24l01_set_tx_mode(void) {
    NRF_CE_LOW;
    // 配置为发送模式，上电
    nrf_write_reg(NRF24L01_REG_CONFIG, 0x0E);
    rt_thread_mdelay(1);
    NRF_CE_HIGH;
    rt_thread_mdelay(1);
}

void nrf24l01_set_rx_mode(void) {
    NRF_CE_LOW;
    // 配置为接收模式，上电
    nrf_write_reg(NRF24L01_REG_CONFIG, 0x0F);
    rt_thread_mdelay(1);
    NRF_CE_HIGH;
    rt_thread_mdelay(1);
}

rt_err_t nrf24l01_send_data(uint8_t *payload, uint8_t len) {
    if (len > PAYLOAD_WIDTH) len = PAYLOAD_WIDTH;

    NRF_CE_LOW;

    // 清除发送FIFO
    nrf_flush_tx();

    // 写入发送数据
    NRF_CS_LOW;
    rt_hw_us_delay(10);
    nrf_spi_transfer(NRF24L01_CMD_W_TX_PAYLOAD);
    for (uint8_t i = 0; i < len; i++) {
        nrf_spi_transfer(payload[i]);
    }
    NRF_CS_HIGH;
    rt_hw_us_delay(10);

    // 启动发送
    NRF_CE_HIGH;
    rt_hw_us_delay(15);  // 至少10us
    NRF_CE_LOW;

    // 等待发送完成或超时
    rt_tick_t start_tick = rt_tick_get();
    while (1) {
        uint8_t status = nrf_read_reg(NRF24L01_REG_STATUS);

        // 发送成功
        if (status & (1 << 5)) {
            nrf_write_reg(NRF24L01_REG_STATUS, 1 << 5);  // 清除TX_DS标志
            return RT_EOK;
        }

        // 发送失败（超过重发次数）
        if (status & (1 << 4)) {
            nrf_write_reg(NRF24L01_REG_STATUS, 1 << 4);  // 清除MAX_RT标志
            nrf_flush_tx();  // 清除发送FIFO
            return -RT_ERROR;
        }

        // 超时检查（100ms）
        if (rt_tick_get() - start_tick > rt_tick_from_millisecond(100)) {
            return -RT_ETIMEOUT;
        }

        rt_thread_mdelay(1);
    }
}

rt_err_t nrf24l01_receive_data(uint8_t *buffer, uint8_t len) {
    if (buffer == RT_NULL || len < PAYLOAD_WIDTH) {
        return -RT_ERROR;
    }

    // 读取接收数据
    NRF_CS_LOW;
    rt_hw_us_delay(10);
    nrf_spi_transfer(NRF24L01_CMD_R_RX_PAYLOAD);
    for (uint8_t i = 0; i < PAYLOAD_WIDTH; i++) {
        buffer[i] = nrf_spi_transfer(0xFF);
    }
    NRF_CS_HIGH;
    rt_hw_us_delay(10);

    // 清除接收标志
    nrf_write_reg(NRF24L01_REG_STATUS, 1 << 6);

    // 清除接收FIFO
    nrf_flush_rx();

    return RT_EOK;
}

rt_bool_t nrf24l01_data_available(void) {
    return (nrf_read_reg(NRF24L01_REG_STATUS) & (1 << 6)) ? RT_TRUE : RT_FALSE;
}

/* ------------------- 主测试线程 ------------------- */
static void nrf_lcd_test_thread(void *param) {
    uint8_t tx_data[PAYLOAD_WIDTH] = {0x01, 0x02, 0x03};
    uint8_t rx_data[PAYLOAD_WIDTH] = {0};
    uint8_t count = 0;
    char str[32];

    // 初始化LCD
    lcd_init();
    lcd_fill_screen(COLOR_BLACK);
    lcd_draw_string(10, 5, "nRF24L01 Test", COLOR_YELLOW);

    // 初始化nRF24L01
    if (nrf24l01_init() != RT_EOK) {
        lcd_draw_string(10, 20, "nRF Init Fail", COLOR_RED);
        while (1) {
            rt_thread_mdelay(1000);
        }
    }
    lcd_draw_string(10, 20, "nRF Init OK", COLOR_GREEN);

    // 显示寄存器信息
    uint8_t config = nrf_read_reg(NRF24L01_REG_CONFIG);
    uint8_t status = nrf_read_reg(NRF24L01_REG_STATUS);
    uint8_t rf_ch = nrf_read_reg(NRF24L01_REG_RF_CH);

    rt_sprintf(str, "CONFIG: 0x%02X", config);
    lcd_draw_string(10, 35, str, COLOR_CYAN);

    rt_sprintf(str, "STATUS: 0x%02X", status);
    lcd_draw_string(10, 45, str, COLOR_CYAN);

    rt_sprintf(str, "RF_CH: 0x%02X", rf_ch);
    lcd_draw_string(10, 55, str, COLOR_CYAN);

    // 主循环：交替发送和接收数据
    while (1) {
        // 发送数据
        nrf24l01_set_tx_mode();
        tx_data[0] = count++;
        tx_data[1] = count * 2;
        tx_data[2] = count + 0x10;

        lcd_clear_area(10, 120, 70, 85, COLOR_BLACK);
        if (nrf24l01_send_data(tx_data, PAYLOAD_WIDTH) == RT_EOK) {
            rt_sprintf(str, "TX: %02X %02X %02X", tx_data[0], tx_data[1], tx_data[2]);
            lcd_draw_string(10, 70, str, COLOR_GREEN);
        } else {
            lcd_draw_string(10, 70, "TX Failed", COLOR_RED);
        }

        rt_thread_mdelay(2000);

        // 接收数据
        nrf24l01_set_rx_mode();
        lcd_clear_area(10, 120, 90, 105, COLOR_BLACK);

        if (nrf24l01_data_available()) {
            if (nrf24l01_receive_data(rx_data, PAYLOAD_WIDTH) == RT_EOK) {
                rt_sprintf(str, "RX: %02X %02X %02X", rx_data[0], rx_data[1], rx_data[2]);
                lcd_draw_string(10, 90, str, COLOR_GREEN);
            } else {
                lcd_draw_string(10, 90, "RX Failed", COLOR_RED);
            }
        } else {
            lcd_draw_string(10, 90, "No RX Data", COLOR_YELLOW);
        }

        rt_thread_mdelay(2000);
    }
}

/* ------------------- 自动初始化 ------------------- */
static int nrf_lcd_init(void) {
    rt_thread_t tid = rt_thread_create(
        "nrf_lcd_test",
        nrf_lcd_test_thread,
        RT_NULL,
        4096,
        RT_THREAD_PRIORITY_MAX / 2,
        20
    );

    if (tid != RT_NULL) {
        rt_thread_startup(tid);
        LOG_I("nRF24L01 LCD test thread created");
    } else {
        LOG_E("Failed to create nRF24L01 LCD test thread");
    }

    return 0;
}
INIT_APP_EXPORT(nrf_lcd_init);
